package com.xiangxiao.rpan.authority.oauth;

import com.google.gson.Gson;
import com.xiangxiao.rpan.authority.constant.ResponseCode;
import com.xiangxiao.rpan.authority.dto.JsonObject;
import com.xiangxiao.rpan.authority.exception.MsgException;
import com.xiangxiao.rpan.authority.service.UserService;
import com.xiangxiao.rpan.authority.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.oauth2.common.exceptions.*;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @auther xiangxiao
 * @email 573768011@qq.com
 * @data 2023/3/25 16:11
 */
@Component
public class LocalLoginExceptionTranslator implements WebResponseExceptionTranslator {
  @Autowired
  private HttpServletRequest request;
  @Autowired
  private HttpServletResponse response;
  @Autowired
  private StringRedisTemplate redisTemplate;
  @Autowired
  private UserService userService;

  @Override
  public ResponseEntity<OAuth2Exception> translate(Exception e) throws Exception {
    JsonObject object = new JsonObject();

    if (e instanceof InvalidGrantException || e instanceof InternalAuthenticationServiceException) {
      object.setRespCode(ResponseCode.LOGIN_ERROR);
      object.setRespMessage("用户名或密码错误");
      if (e.getCause() instanceof MsgException) {
        object.setRespMessage(e.getMessage());
        object.setRespCode(((MsgException) e.getCause()).getErrorCode());
      }
    } else if (e instanceof InvalidRequestException) {
      object.setRespCode(ResponseCode.INVALID_REQUEST_ERROR);
      object.setRespMessage("不支持的请求类型");
    } else if (e instanceof InvalidTokenException) {
      object.setRespCode(ResponseCode.NO_LOGIN);
      object.setRespMessage("没有登录或者token错误");
    } else if (e instanceof BadClientCredentialsException || e instanceof UnauthorizedClientException) {
      object.setRespCode(ResponseCode.NO_ACCESS);
      object.setRespMessage("权限验证不通过");
    } else if (e instanceof MsgException) {
      MsgException exception = (MsgException) e;
      object.setRespCode((exception.getErrorCode()));
      object.setRespMessage(exception.getMessage());
    }
    Gson gson = new Gson();
    response.setContentType("application/json;charset=utf-8");
    response.getWriter().write(gson.toJson(object));
    return null;
  }
}
